package me.numark.fragments;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.squareup.picasso.Picasso;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import me.numark.MainActivity;
import me.numark.R;
import me.numark.model.CombinedComment;
import me.numark.model.CombinedCommentResponse;
import me.numark.net.GsonRequest;
import me.numark.net.NetworkConstants;
import me.numark.net.NetworkHelper;
import me.numark.utils.Constants;
import me.numark.utils.LogUtils;
import me.numark.utils.Settings;
import me.numark.utils.Utils;
import me.numark.view.CircleImageView;

/**
 * Created by tian on 14/11/10:下午10:04.
 */
public class CommentsFragment extends Fragment implements
        AdapterView.OnItemClickListener, PullToRefreshBase.OnRefreshListener2<ListView> {

    private PullToRefreshListView mList;

    private CommentsAdapter mAdapter;

    private String mUserId;

    private int basePadding;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_news_feed, container, false);
        basePadding = Utils.dp2px(getActivity(), 12);
        mList = (PullToRefreshListView) view.findViewById(R.id.ptr_list);
        mList.setOnRefreshListener(this);
        mAdapter = new CommentsAdapter();
        mList.setAdapter(mAdapter);
        if (getArguments() != null) {
            mUserId = getArguments().getString(ProfileFragment.USER_ID, Settings.getUid());
        }
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        mList.setState(PullToRefreshBase.State.INIT_REFRESHING, true);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        loadComments(0);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        loadComments(mResponseList.size());
    }

    private void loadComments(int start) {
        Activity container = getActivity();
        String url;
        if (container instanceof MainActivity) {
            url = String.format(NetworkConstants.SHARE_COMMENTS_URL, mUserId)
                    + "?start=" + start + "&limit=" + Constants.PAGE_SIZE;
        } else {
            url = String.format(NetworkConstants.MY_SHARE_COMMENTS_URL, Settings.getUid())
                    + "?start=" + start + "&limit=" + Constants.PAGE_SIZE;
        }
        GsonRequest<CombinedCommentResponse> request = new GsonRequest<CombinedCommentResponse>(url,
                Request.Method.GET,
                CombinedCommentResponse.class, true, null,
                new Response.Listener<CombinedCommentResponse>() {
                    @Override
                    public void onResponse(CombinedCommentResponse response) {
                        LogUtils.d(
                                "response is " + response.ret);
                        if (response.ret && response.data != null) {
                            Collections.addAll(mResponseList, response.data);
                        }
                        finishLoading();
                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                finishLoading();
                error.printStackTrace();
            }
        });
        NetworkHelper.getInstance().addToRequestQueue(request);
        NetworkHelper.getInstance().getRequestQueue().start();
    }

    private class CommentsAdapter extends BaseAdapter {

        Date today, yesterday, year;

        public CommentsAdapter() {
            super();
            Date[] dates = Utils.getMarkDate();
            today = dates[0];
            yesterday = dates[1];
            year = dates[2];
        }

        @Override
        public int getCount() {
            return mResponseList.size();
        }

        @Override
        public CombinedComment getItem(int position) {
            return mResponseList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View view, ViewGroup parent) {
            ViewHolder holder;
            if (view != null) {
                holder = (ViewHolder) view.getTag();
            } else {
                view = getActivity().getLayoutInflater().inflate(R.layout.comment_list_item, parent,
                        false);
                holder = new ViewHolder(view);
                view.setTag(holder);
            }
            CombinedComment comment = getItem(position);
            if (!TextUtils.isEmpty(comment.comments[0].user.pic)) {
                Picasso.with(getActivity()).load(comment.comments[0].user.pic).into(holder.avatar);
            }
            holder.nick.setText(comment.comments[0].user.nick);
            holder.comment_time.setText(
                    Utils.getTimeShowText(comment.comments[0].getDate(), yesterday, today, year));
            holder.comment.setText(comment.comments[0].description);
            if (!TextUtils.isEmpty(comment.feed.news.face_img)) {
                Picasso.with(getActivity()).load(comment.feed.news.face_img).into(holder.icon);
            }
            holder.title.setText(comment.feed.news.title);
            holder.newsTime.setText(
                    Utils.getTimeShowText(comment.feed.news.getDate(), yesterday, today, year));
            holder.source.setText(comment.feed.news.from_str);
            holder.news.setBackgroundColor(getResources().getColor(R.color.feed_news_item_bg));
            if (TextUtils.isEmpty(mUserId)) {
                view.setPadding(basePadding, 0, basePadding, 0);
            }
            return view;
        }
    }

    static class ViewHolder {

        @InjectView(R.id.avatar)
        CircleImageView avatar;

        @InjectView(R.id.nick)
        TextView nick;

        @InjectView(R.id.comment_time)
        TextView comment_time;

        @InjectView(R.id.comment)
        TextView comment;

        @InjectView(R.id.news_icon)
        ImageView icon;

        @InjectView(R.id.news_title)
        TextView title;

        @InjectView(R.id.news_time)
        TextView newsTime;

        @InjectView(R.id.news_source)
        TextView source;

        @InjectView(R.id.news)
        View news;

        public ViewHolder(View view) {
            ButterKnife.inject(this, view);
        }

    }

    private void finishLoading() {
        mList.postDelayed(new Runnable() {
            @Override
            public void run() {
                mList.onRefreshComplete();
            }
        }, 100);
        mAdapter.notifyDataSetChanged();
    }

    private List<CombinedComment> mResponseList = new ArrayList<CombinedComment>();

}
